require(['init'], function () {
   var $J_teacher_appoint = $('<div class="teacher-appoint" id="J_teacher_appoint" style="width:100%;">' +
               '<input type="hidden" id="oruid">' +
               '<input type="hidden" class="studentuid">' +
                '<input class="form-control " type="hidden" id="studentname">' +
                '<input class="form-control " type="hidden" id="coursename" >' +
                '<div class="line"></div>' +
                '<div class="TeachersQuery" style="width: 55%; float: left; border-bottom：none !important; height:100%; margin-top: 20px; border-radius: 5px">' +
                '<div class="topbar clearafter" style="margin-left:15px;height:94px">' +
                '<div class="teacher-search">' +
                '<p><a href="javascript:;">学生姓名：</a><span id="studentname1" style="margin-right:15px;"></span>' +
                '<a href="javascript:;">课程：</a><span id="coursename1" style="margin-right:52px;"></span></p><br/>' +
                '<span>教师查询：</span>' +
                '<input type="text" id="J_date_search" class="form-control" data-type="date-input" data-tips="请选择日期范围" data-valuetype="range" readonly="" value="请选择日期范围" style="width: 210px;">' +
                '<select id="cource"></select>' +
                '</div>' +
                '</div>' +
                '<div class="wrap" id="appint_alert">' +
                '<table class="table" id="J_teacherlist_select">' +
                '<thead>' +
                '<th>No</th>' +
                '<th>名字</th>' +
                '<th>开始时间</th>' +
                '<th>结束时间</th>' +
                 '<th>剩余名额</th>' +
                 '<th>选择</th>' +
               '</thead>' +
               '<tbody id="J_teacherlist_data"></tbody>' +
               '</table>' +
             '</div>' +
             '</div>' +
              '<div class="timelist-search" style="width: 42%; float: right; margin-left: 30px; border-bottom：none; height:auto;  border-left: 1px solid #ccc; margin-top: 20px;">' +
             '<h3 style="margin-left:15px;">预约</h3>' +
             '<div class="teacher" style="margin-left:15px;">' +
             '<span>教师姓名：</span>' +
             '<span id="J_teachername"></span>' +
             '<ul class="teacherRemark" style="display:inline-block;margin-left:30px;"></ul>'+
             '</div>' +
             '<div class="duration" style="margin-left:15px;"></div>' +
             '<div class="appoint-section23" style="margin-left:15px;" id="appint_sealert"></div>' +
             '</div>' +
             '<div style="width: 42%; float: right; margin-left: 30px; border-bottom：none; height: 980px;  border-left: 1px solid #ccc; margin-top: 20px;display:none" class="prompt">' +
             '<p style="margin-top:154px;margin-left:77px;">请点击左侧的选择按钮显示预约时间段</p>' +
             '</div>' +
       '</div>');
   var $orderEdit = $('<div class="paraList Nformstyle" id="J_enroll_wrap" >' +
            '<input class="form-control " type="hidden" name="orderuid">' +
            '<input class="form-control " type="hidden" name="studentuid" >' +
            '<div class="li Snameinput">' +
            '<div class="title  required">' +
              '<span>学生姓名：</span>' +
            '</div>' +
            '<div class="content">' +
              '<input class="form-control a1 focus studentname" data-formcheck="length" type="text" name="studentname"  readonly>' +
              '<div class="inputErrorTips" style="display: none;"></div>' +
            '</div>' +

            ' </div>' +
          '<div class="li">' +
            '<div class="title required">' +
              '<span>ClassIn账号：</span>' +
            '</div>' +
            '<div class="content">' +
              '<input class="form-control focus a1" type="text" name="ClassInNo"  readonly>' +
              '<div class="inputErrorTips" style="display: none;"></div>' +
            '</div>' +
          '</div>' +
          '<div class="li">' +
            '<div class="title">' +
              '<span>课&nbsp&nbsp时&nbsp&nbsp数：</span>' +
            '</div>' +
            '<div class="content">' +
              '<input class="form-control a1" type="text" name="classhours" >' +
            '</div>' +
          '</div>' +
          '<div class="li">' +
            '<div class="title">' +
              '<span>赠送课时：</span>' +
            '</div>' +
            '<div class="content">' +
              '<input class="form-control a1" type="text" name="classbonus" >' +
            '</div>' +
          '</div>' +
          '<div class="li">' +
            '<div class="title">' +
              '<span>课程名称：</span>' +
            '</div>' +
            '<div class="content">' +
              '<input class="form-control a1" type="text" name="coursename" >' +
            '</div>' +
          '</div>' +

          '<div class="li">' +
            '<div class="title">' +
              '<span>录入日期：</span>' +
            '</div>' +
            '<div class="content">' +
              '<input type="text" class="form-control a1" size="16" data-type="date-input" name="orderdate" data-valuetype="single" data-value="0" value="选择时间" readonly="readonly"  style="width:177px;">' +
              '</div>' +
          '</div>' +

          '<div class="li">' +
            '<div class="title">' +
              '<span>描&nbsp&nbsp&nbsp&nbsp&nbsp述：</span>' +
            '</div>' +
            '<div class="content">' +
              '<input class="form-control a1" type="text" name="description" >' +
            '</div>' +
          '</div>' +
          '<div class="li">' +
            '<div class="title">' +
              '<span>金&nbsp&nbsp&nbsp&nbsp&nbsp额：</span>' +
            '</div>' +
            '<div class="content" style="position:relative;">' +
              '<input class="form-control a1" type="text" name="amount" style="padding-left:15px;width:177px" id="ordersinputpadding">' +
              '<span style="position:absolute;left:5px;top:6px" id="orderspanhide">￥</span>' +
            '</div>' +
          '</div>' +

        '</div>');
        $J_teacher_appoint.find('.line').css({
            "width": "1px",
            "height": "326px",
            "background": "#ccc",
            "position": "absolute",
            "left": "598px",
            "top": "30px",
            "z-index": "10000"
        })
   var $orderAdd;
   var uid;
   var currentid;
   $.ajax({
     url:"/api/user/current",
     type:"get",
     async:false,
     success:function(data){
       //console.log(data.data.userid)
       uid=data.data.userid;

    }
   })
   $.ajax({
     url:"/api/student/user/"+uid,
     type:"get",
     async:false,
     success:function(data){
        currentid=data.data.studentuid;
     }
   })

  //获取当前学生的课程信息
   getorderinfos();
   function getorderinfos(query) {
    ajaxMethod({
      url: '/api/appoint/myclasses/'+currentid,
      type: 'get',
      data: query,
      success: function (data) {
        var $enrollmentTable = $('#J_enrollment').html('')
        if(data.length==0){
          var $div=$('<div style="font-size:14px;height:166px;border-top: 1px solid #ccc;line-height:166px;margin-top:19px;text-align: center;">您还没有购买课程,请先去够买课程!</div>').appendTo($enrollmentTable);
        }else{
          getorderinfossuccess(data);
        }

       }
    })

    function getorderinfossuccess(data) {
        var $enrollmentTable = $('#J_enrollment').html('')
        var $thead = $('<thead>\
          <tr>\
            <th>No</th>\
            <th>课程名称</th>\
            <th>课时数</th>\
            <th>赠送课时</th>\
            <th>总课时<small style="font-size:6px;">（课时数+赠送课时）</small></th>\
            <th>已约课时</th>\
            <th><a herf="javascript:;" >录入日期</a></th>\
            <th>录入人</th>\
            <th>操作</th>\
         </tr>\
         </thead>').appendTo($enrollmentTable)
        var $tbody = $('<tbody></tbody>').appendTo($enrollmentTable);
        //data = JSON.parse(data)
        $.each(data, function (index, item) {
          console.log(item)
          var item=item.appoint;
          //转化成数字
            var classhours=Number(item.classhours);
            var classbonus=Number(item.classbonus)
            var coursename="";
            if(item.coursename!=""){
              coursename=item.coursename;
            }else{
               coursename="--";
            }
            var oruid = item.appointid;
            var studentuid = item.studentuid;
            var sum = (item.classhours) + (item.classbonus);
            var orderTime = formatTime(item.orderdate);
            var $enroll = $('<tr class="enroll" data-uid="' + oruid + '"   data-studentuid="' + studentuid + '"  id="oder' + oruid + '"></tr>')
            $enroll.append('<td>1</td>')
            $enroll.append('<td>' + coursename + '</td>')
            // $enroll.append('<td>' + item.studentname + '</td>')
            // $enroll.append('<td>' + item.ClassInNo + '</td>')//这里的mobile实际是classInNo的字段
            $enroll.append('<td  >' + classhours+ '</td>')
            $enroll.append('<td >' +classbonus+ '</td>')
            $enroll.append('<td >' + (classhours+classbonus) + '</td>')
            var $alreadyhours = $('<td ><input type="button" class="btn btn-primary btn-sm btn-inverse appointhours"  value=' + item.consumed + '  style="background:#fff;"></td>').appendTo($enroll);
            $enroll.append('<td>' + orderTime.substr(0, 10) + '</td>')
            $enroll.append('<td>' + item.creator + '</td>')
            var $bookbtn = $('<td ><input type="button" value="约课" class="ml5 btn btn-primary btn-sm btn-inverse" nam="arrbook" style="background:#fff;"></td>').appendTo($enroll);
            var $handleTd = $('<td></td>').appendTo($enroll);
            var $deletebtn = $('<a class="ml5 editOrder" style="display:none"><span class="btn btn-primary btn-sm btn-inverse" >编辑</span></a>').appendTo($handleTd);
            var $debtn = $('<a href="javascript:;" style="display:none"><span class="	btn btn-danger btn-sm btn-inverse">删除</span></a>').appendTo($handleTd);

            var sumn= (classhours + classbonus);
            var inputVlue= parseInt($alreadyhours.find('input').val());
            if(inputVlue>=sumn){
                $bookbtn.find("input").attr("disabled","disabled");
              //  $bookbtn.find("input").css({"background":"#ccc","border":"1px solid #ada7a7","color":"#fff"})
               }else{
                $bookbtn.find("input").removeAttr("disabled");
               }
             //点击约课
               $bookbtn.on('click', function () {
                $J_teacher_appoint.find("#oruid").val(item.appointid);
                $J_teacher_appoint.find(".studentuid").val(studentuid);
                $J_teacher_appoint.find('#studentname').val(item.studentname);
                $J_teacher_appoint.find('#coursename').val(item.coursename);
                appointTeacher();//按照时间选择老师
                coursetypes();//按照课程类型选择老师
                var popUpBox = new PopUpBox({
                    type: 'dom',
                    style: 'default autoResize',
                    submitBtnType:'alert',
                    closeClear:false,
                    titleText: '请选择老师',
                    show: true,
                    content: $J_teacher_appoint,
                    callback: {
                        yes: function (e) {
                          window.location.reload();
                        }
                    },
                    position: {
                        width: 1042,
                        height: 510,
                    }
                })
                popUpBox.submitBtnBox.$dom.css('text-align', 'right')
              })
           //点击编辑按钮
            $deletebtn.on('click', function () {
                loadEnrollData(oruid);
                var popUpBox = new PopUpBox({
                    type: 'dom',
                    style: 'default contentScroll',
                    submitBtnType: 'confirm',
                    titleText: '请输入编辑内容',
                    show: true,
                    content: $orderEdit,
                    callback: {
                        yes: function (e) {
                            // alert(this);
                            bindSubmit();
                            window.location.reload();

                        }
                    },
                    position: {
                        width: 667,
                        height: 352
                    }
                })
            })
          //点击删除按钮
          $debtn.on('click', function () {
              var popUpBox = new PopUpBox({
                  type: 'dom',
                  style: 'default contentScroll',
                  submitBtnType: 'confirm',

                  titleText: '温馨提示',
                  show: true,
                  content: "<div style='margin-left:27px;margin-top:34px;'>学生信息会一并删除，确定要删除吗？</div>",
                  callback: {
                      yes: function (e) {
                          ajaxMethod({
                              url: "/api/appointment/" + oruid,
                              type: "delete",
                              success: function () {
                                  getorderinfos();

                              }
                          });
                      }
                  },
                  position: {
                      width: 448,
                      height: 226
                  }
              })


          })
          $tbody.append($enroll);
          //table排序
          var len = $('table tr').length;
          for (var i = 1; i < len; i++) {
              $('table tr:eq(' + i + ') td:first').text(i);
          }

        //处理空数据
        $tbody.find("tr").each(function () {
            var tdhtml = $(this).children();
            $.each(tdhtml, function (i, t) {
                //console.log($(t).text());
                $(t).text() == 'null' ? $(t).text('--') : $(t).text()
                $(t).text() == 'NaNaN-aN-a' ? $(t).text('--') : $(t).text()
                $(t).text() == ' ' ? $(t).text('--') : $(t).text()
                $(t).text() == '0000-00-00' ? $(t).text('--') : $(t).text()

            })
        });
        //已约课按钮设置
        var $appointhours = $alreadyhours.find("input");
        if (item.consumed == 0) {
            $appointhours.attr('disabled', true);
        } else {
            $appointhours.attr('disabled', false);
        }

        //点击已约课时数量
        $alreadyhours.on("click", function () {
        ajaxMethod({
              url: '/api/appointment/'+oruid+'/appints',
              type: 'get',
              dataType: 'json',
              success: function (data) {
                  var $div = $('<div class="Yuelist wrap"></div>')
                  var $table = $('<table class="table enrollment" id="YueClasslist" style="margin-top:15px;"></table>').appendTo(($div));;
                  var $thead = $('<thead>\
                                    <tr>\
                                      <th>No</th>\
                                      <th>教师姓名</th>\
                                      <th>开始日期</th>\
                                      <th>时间</th>\
                                      <th>时长</th>\
                                      <th>操作</th>\
                                    </tr>\
                                    </thead>').appendTo($table);
                  var $tbody = $('<tbody></tbody>').appendTo($table);
                  function getDurationMinute(begintime, endtime) {
                      if (begintime != null || endtime != null) {
                          var begintime = +new Date(begintime.replace(' ', ' '));
                          var endtime = +new Date(endtime.replace(' ', ' '));
                          return (endtime - begintime) / (60 * 1000) + '分钟';
                      } else {
                          return '--';
                      }
                  }
                  $.each(data, function (index, item) {
                    var id=item.id;var uid = item.scheduleid;
                    var begintime = new Date(item.begintime).Format('YYYY-MM-DD hh:mm')
                    var endtime = new Date(item.endtime).Format('YYYY-MM-DD hh:mm');
                    var $valuetr = $('<tr class="enroll" data-uid="' + uid + '"></tr>')
                    $valuetr.append('<td>1</td>')
                    $valuetr.append('<td>' + item.teacher + '</td>')
                    $valuetr.append('<td>' + begintime.substr(0,10) + ' </td>')
                    $valuetr.append('<td>' + begintime.substr(11,5) + '</td>')
                    $valuetr.append('<td>' + getDurationMinute(item.begintime, item.endtime) + '</td>')
                    var $affirm = $('<td><a  class="ml5 btn btn-warning">取消</a></td>').appendTo($valuetr);
                    $affirm.on('click', function () {
                        ajaxMethod({
                            url: '/api/appointment/'+id+'/unappint',
                            type: 'put',
                            success: function (data) {
                                window.location.reload();
                                $('.popUpBoxBg').css('display', 'none');
                                $('.popUpBoxFg').css('display', 'none');

                            }

                        })
                    })

                      $tbody.append($valuetr);
                      //table排序
                      var len = $div.find('table tr').length;
                      for (var i = 1; i < len; i++) {
                          $div.find('table tr:eq(' + i + ') td:first').text(i);
                      }
                  })
                  //弹出层
                  var popUpBox = new PopUpBox({
                      type: 'dom',
                      style: 'default contentScroll',
                      submitBtnType: false,
                      titleText: '学生姓名:　<span>' + item.studentname + '</span>',
                      show: true,
                      content: $div,
                      callback: {
                          yes: function (e) {
                              //alert("hello")
                          }
                      },
                      position: {
                          width: 871,
                          height: 500
                      }
                  })

              }
          })
      })
        })
        //把所有null的字段都换成---
        $tbody.find("tr").each(function () {
            var tdhtml = $(this).children();
              $.each(tdhtml, function (i, t) {
                $(t).text() == 'null' ? $(t).text('--') : $(t).text()
                $(t).text() == '1970-01-01' ? $(t).text('--') : $(t).text()
            })
        });

    }

    }

   //报名表列表导入功能
   function fileUpload($container) {
       var $uploadInput = $container.find('input')
       var coverUploadInput = new UploadInput({
         formData: {
           importer: 'appoint'
         },
         $dom: $uploadInput,
         done: function (uploadSrc) {
           //console.log(uploadSrc);
          window.location.reload();
         }
       });
   }

  fileUpload($('#J_container'))
   //搜索
  $('#J_teacher_search').on('click', function (data) {
           var nameval = $('.searchInput').val();
           if (nameval == "") {
               return false;
           } else {
                ajaxMethod({
                   url: "/api/appointments",
                   data: {
                       "studentname": nameval,
                       "ClassIn": nameval
                   },

                   success: function (data) {
                       Thequeryssuccess(data.list);
                   }
               })
               function Thequeryssuccess(data) {
                   var $enrollmentTable = $('#J_enrollment').html('')
                   var $thead = $('<thead>\
                     <tr>\
                       <th>No</th>\
                       <th>课程名称</th>\
                       <th>课时数</th>\
                       <th>赠送课时</th>\
                       <th>总课时<small style="font-size:6px;">（课时数+赠送课时）</small></th>\
                       <th>已约课时</th>\
                       <th><a herf="javascript:;" >录入日期</a></th>\
                       <th>录入人</th>\
                       <th>操作</th>\
                    </tr>\
                    </thead>').appendTo($enrollmentTable)
                   var $tbody = $('<tbody></tbody>').appendTo($enrollmentTable);
                   //data = JSON.parse(data)
                   $.each(data, function (index, item) {
                     var classhours=Number(item.classhours);
                     var classbonus=Number(item.classbonus)
                       var coursename="";
                       if(item.coursename!=""){
                         coursename=item.coursename;
                       }else{
                          coursename="--";
                       }
                       var oruid = item.appointid;
                       var studentuid = item.studentuid;
                       var sum = (item.classhours) + (item.classbonus);
                       var orderTime = formatTime(item.orderdate);
                       var $enroll = $('<tr class="enroll" data-uid="' + oruid + '"   data-studentuid="' + studentuid + '"  id="oder' + oruid + '"></tr>')
                       $enroll.append('<td>1</td>')
                       $enroll.append('<td>' + coursename + '</td>')
                      //  $enroll.append('<td>' + item.studentname + '</td>')
                      //  $enroll.append('<td>' + item.ClassInNo + '</td>')
                       $enroll.append('<td  >' + classhours + '</td>')
                       $enroll.append('<td >' + classbonus + '</td>')
                       $enroll.append('<td >' + (classhours + classbonus) + '</td>')
                       var $alreadyhours = $('<td ><input type="button" class="btn btn-primary btn-sm btn-inverse appointhours"  value=' + item.consumed + '  style="background:#fff;"></td>').appendTo($enroll);
                       $enroll.append('<td>' + orderTime.substr(0, 10) + '</td>')
                       $enroll.append('<td>' + item.creator + '</td>')
                       var $bookbtn = $('<td ><input type="button" value="约课" class="ml5 btn btn-primary btn-sm btn-inverse" nam="arrbook" style="background:#fff;"></td>').appendTo($enroll);
                       var $handleTd = $('<td></td>').appendTo($enroll);
                       var $deletebtn = $('<a class="ml5 editOrder"  style="display:none"><span class="	btn btn-primary btn-sm btn-inverse" >编辑</span></a>').appendTo($handleTd);
                       var $debtn = $('<a href="javascript:(void);" style="display:none"><span class="	btn btn-danger btn-sm btn-inverse">删除</span></a>').appendTo($handleTd);
                       //如果总课时等于已约课时的时候，预约按钮不可用
                      var sumn= (classhours + classbonus);
                       var inputVlue= parseInt($alreadyhours.find('input').val());
                       if(inputVlue>=sumn){
                           $bookbtn.find("input").attr("disabled","disabled");
                           $bookbtn.find("input").css({"background":"#ccc","border":"1px solid #ada7a7","color":"#fff"})
                          }else{
                           $bookbtn.find("input").removeAttr("disabled");
                          }
                          //点击约课的时候跳转页面和传递参数
                          $bookbtn.on('click', function () {
                           $J_teacher_appoint.find("#oruid").val(item.appointid);
                           $J_teacher_appoint.find(".studentuid").val(studentuid);
                           $J_teacher_appoint.find('#studentname').val(item.studentname);
                           $J_teacher_appoint.find('#coursename').val(item.coursename);
                           appointTeacher();//按照时间选择老师
                           coursetypes();//按照课程类型选择老师
                           var popUpBox = new PopUpBox({
                               type: 'dom',
                               style: 'default autoResize',
                               submitBtnType:'alert',
                               closeClear:false,
                               titleText: '请选择老师',
                               show: true,
                               content: $J_teacher_appoint,
                               callback: {
                                   yes: function (e) {
                                     window.location.reload();
                                   }

                               },
                               position: {
                                   width: 1042,
                                   height: 510,
                               }
                           })
                           popUpBox.submitBtnBox.$dom.css('text-align', 'right')
                         })
                      //点击编辑按钮
                       $deletebtn.on('click', function () {
                           loadEnrollData(oruid);
                           var popUpBox = new PopUpBox({
                               type: 'dom',
                               style: 'default contentScroll',
                               submitBtnType: 'confirm',
                               titleText: '请输入编辑内容',
                               show: true,
                               content: $orderEdit,
                               callback: {
                                   yes: function (e) {
                                       // alert(this);
                                       bindSubmit();
                                       window.location.reload();

                                   }
                               },
                               position: {
                                   width: 667,
                                   height: 352
                               }
                           })
                       })
                     //点击删除按钮
                     $debtn.on('click', function () {
                         var popUpBox = new PopUpBox({
                             type: 'dom',
                             style: 'default contentScroll',
                             submitBtnType: 'confirm',

                             titleText: '温馨提示',
                             show: true,
                             content: "<div style='margin-left:27px;margin-top:34px;'>学生信息会一并删除，确定要删除吗？</div>",
                             callback: {
                                 yes: function (e) {
                                     ajaxMethod({
                                         url: "/api/appointment/" + oruid,
                                         type: "delete",
                                         success: function () {
                                             getorderinfos();

                                         }
                                     });
                                 }
                             },
                             position: {
                                 width: 448,
                                 height: 226
                             }
                         })


                     })
                     $tbody.append($enroll);
                     //table排序
                     var len = $('table tr').length;
                     for (var i = 1; i < len; i++) {
                         $('table tr:eq(' + i + ') td:first').text(i);
                     }

                   //处理空数据
                   $tbody.find("tr").each(function () {
                       var tdhtml = $(this).children();
                       $.each(tdhtml, function (i, t) {
                           //console.log($(t).text());
                           $(t).text() == 'null' ? $(t).text('--') : $(t).text()
                           $(t).text() == 'NaNaN-aN-a' ? $(t).text('--') : $(t).text()
                           $(t).text() == ' ' ? $(t).text('--') : $(t).text()
                           $(t).text() == '0000-00-00' ? $(t).text('--') : $(t).text()

                       })
                   });
                   //已约课按钮设置
                   var $appointhours = $alreadyhours.find("input");
                   if (item.consumed == 0) {
                       $appointhours.attr('disabled', true);
                   } else {
                       $appointhours.attr('disabled', false);
                   }

                   //点击已约课时数量
                   $alreadyhours.on("click", function () {
                   ajaxMethod({
                         url: '/api/appointment/'+oruid+'/appints',
                         type: 'get',
                         dataType: 'json',
                         success: function (data) {
                             // console.log(data)
                             var $div = $('<div class="Yuelist wrap"></div>')
                             var $table = $('<table class="table enrollment" id="YueClasslist" style="margin-top:15px;"></table>').appendTo(($div));;
                             var $thead = $('<thead>\
                                               <tr>\
                                                 <th>No</th>\
                                                 <th>教师姓名</th>\
                                                 <th>开始日期</th>\
                                                 <th>时间</th>\
                                                 <th>时长</th>\
                                                 <th>操作</th>\
                                               </tr>\
                                               </thead>').appendTo($table);
                             var $tbody = $('<tbody></tbody>').appendTo($table);
                             function getDurationMinute(begintime, endtime) {
                                 if (begintime != null || endtime != null) {
                                     var begintime = +new Date(begintime.replace(' ', ' '));
                                     var endtime = +new Date(endtime.replace(' ', ' '));
                                     return (endtime - begintime) / (60 * 1000) + '分钟';
                                 } else {
                                     return '--';
                                 }
                             }
                             //data = JSON.parse(data)
                             $.each(data, function (index, item) {
                                var id=item.id;
                                 //console.log(item);
                                 var uid = item.scheduleid;
                                 //var bgT = formatTime(item.begintime)
                                 //var edT = formatTime(item.endtime)
                                 var begintime = new Date(item.begintime).Format('YYYY-MM-DD hh:mm')
                                 var endtime = new Date(item.endtime).Format('YYYY-MM-DD hh:mm');
                                 var $valuetr = $('<tr class="enroll" data-uid="' + uid + '"></tr>')
                                 $valuetr.append('<td>1</td>')
                                 $valuetr.append('<td>' + item.teacher + '</td>')
                                 $valuetr.append('<td>' + begintime.substr(0,10) + ' </td>')
                                 $valuetr.append('<td>' + begintime.substr(11,5) + '</td>')
                                 $valuetr.append('<td>' + getDurationMinute(item.begintime, item.endtime) + '</td>')
                                 var $affirm = $('<td><a  class="ml5 btn btn-warning">取消</a></td>').appendTo($valuetr);
                                 $affirm.on('click', function () {
                                     ajaxMethod({
                                         url: '/api/appointment/'+id+'/unappint',
                                         type: 'put',
                                         success: function (data) {
                                             //console.log(data);
                                             window.location.reload();
                                             $('.popUpBoxBg').css('display', 'none');
                                             $('.popUpBoxFg').css('display', 'none');

                                         }

                                     })
                                 })

                                 $tbody.append($valuetr);
                                 //table排序
                                 var len = $div.find('table tr').length;
                                 for (var i = 1; i < len; i++) {
                                     $div.find('table tr:eq(' + i + ') td:first').text(i);
                                 }
                             })
                             //弹出层
                             var popUpBox = new PopUpBox({
                                 type: 'dom',
                                 style: 'default contentScroll',
                                 submitBtnType: false,
                                 //submitBtnType: 'alert',
                                 titleText: '学生姓名:　<span>' + item.studentname + '</span>',
                                 show: true,
                                 content: $div,
                                 callback: {
                                     yes: function (e) {
                                         //alert("hello")
                                     }
                                 },
                                 position: {
                                     width: 871,
                                     height: 500
                                 }
                             })

                         }
                     })
                 })
                   })
                   //把所有null的字段都换成---
                   $tbody.find("tr").each(function () {
                       // console.log(this)
                       var tdhtml = $(this).children();

                       $.each(tdhtml, function (i, t) {
                           //console.log($(t).text());
                           //console.log(t)
                           $(t).text() == 'null' ? $(t).text('--') : $(t).text()
                           $(t).text() == '1970-01-01' ? $(t).text('--') : $(t).text()
                       })
                   });


           }

       }
    })
  //添加学生
    $("#orderadd").on("click", function () {
    $orderAdd = $('<div class="paraList">' +
        '<input class="form-control " type="hidden" name="orderuid">'+
        '<input class="form-control " type="hidden" name="studentuid" >' +
       '<div class="li line">'+
        '<div class="title">'+
          '<label style="color:red";position: relative;left: -2px;>*</label><span>学生姓名</span>' +
        '</div>'+
        '<div class="content" id="j-studencontainer">'+
          '<span class="btn btn-default" id="j-addstudent">添加学生</span>'+
        '</div>'+
      '</div>'+
      '<div class="li">'+
        '<div class="title">'+
          '<label style="color:red";position: relative;left: -2px;>*</label><span>课时数</span>' +
        '</div>'+
        '<div class="content">'+
          '<input class="form-control a1" type="text" name="classhours" >' +
        '</div>'+
      '</div>'+
      '<div class="li">'+
        '<div class="title">'+
          '<span>赠送课时</span>'+
        '</div>'+
        '<div class="content">'+
          '<input class="form-control a1" type="text" name="classbonus" >' +
        '</div>'+
      '</div>'+
      '<div class="li">'+
        '<div class="title">'+
          '<span>课程名称</span>'+
        '</div>'+
        '<div class="content">'+
          '<input class="form-control a1" type="text" name="coursename" >' +
        '</div>'+
      '</div>'+

      '<div class="li">' +
        '<div class="title">' +
          '<span>录入日期</span>' +
        '</div>' +
        '<div class="content">' +
          '<input type="text" class="form-control a1" size="16" data-type="date-input" name="orderdate" data-valuetype="single" data-value="0" value="选择时间" readonly="readonly"  style="width:170px;">' +
          '</div>' +
      '</div>' +

      '<div class="li">'+
        '<div class="title">'+
          '<span>描述</span>'+
        '</div>'+
        '<div class="content">'+
          '<input class="form-control a1" type="text" name="description" ">' +
        '</div>'+
      '</div>'+
      '<div class="li">'+
        '<div class="title">'+
          '<span>金额</span>' +
        '</div>'+
        '<div class="content" style="position:relative;">'+
          '<input class="form-control a1" type="text" name="amount" style="padding-left:15px;width:177px" id="ordersinputpadding" >' +
          '<span style="position:absolute;left:5px;top:7px" id="orderspanhide">￥</span>' +
        '</div>'+
      '</div>'+
    '</div>');
    var newda= new Date().Format('YYYY-MM-DD');
    $orderAdd.find('[name=orderdate]').val(newda);

      var $addStudentBtn = $orderAdd.find('#j-addstudent')
      var studentViewList = new ContactViewList({
        hasAvatar: true,
        editable: false
      })

      $addStudentBtn.after(studentViewList.$dom.addClass('inline-block').addClass('cursor-pointer'))

      function studentSelect() {
        ajaxMethod({
          url: '/api/students',
           success: function (data) {
            var candidateStudentList = []
            $.each(data.list, function (i, item) {
              //console.log(item);
              candidateStudentList.push({
                id: item.studentuid,
                avatar: 'img/avatar.png',
                name: item.name,
                phone: item.ClassInNo
              })
            })

            var studentSelector = new ContactSelector({
              candidateDataList: candidateStudentList,
              checkedDataList: studentViewList.getDataList(),
              checkedMax: 1,
              callback: {
                submit: function (checkedDataList) {
                  if( !Object.keys(checkedDataList).length ) {
                    _Tips('请选择');
                    return false
                  }
                  //console.log(checkedDataList);
                  $addStudentBtn.hide()

                  studentViewList.update(checkedDataList)
                }
              }
            })
            studentSelector.$titleText.html('添加学生')
            studentSelector.popUpBox.show();
          }
        })
      }


      $addStudentBtn.on('click', function () {
        studentSelect();
      })

      studentViewList.$dom.on('click', function() {
        studentSelect();
      })


      var popUpBox = new PopUpBox({
        type: 'dom',
        style: 'default contentScroll',
        submitBtnType: 'confirm',
        titleText: '请填写内容',
        show: true,
        content: $orderAdd,
        callback: {
          yes: function (e) {
            var $contact = $orderAdd.find('.contact');
            function add(){
              var appointid = $orderAdd.find('[name=orderuid]').val()
              var orderstatus = $orderAdd.find('[name=orderstatus]').val()
              var studentuid = $contact.attr('data-contactid');
              var studentname = $contact.find('.name').text();
              var mobile = $contact.find('.description').text();//选框组件
              var classhours = $orderAdd.find('[name=classhours]').val()
              var classbonus = $orderAdd.find('[name=classbonus]').val()
              var courseid = $orderAdd.find('[name=courseid]').val()
              var coursename = $orderAdd.find('[name=coursename]').val()
              var orderdate = $orderAdd.find('[name=orderdate]').val()
              var description = $orderAdd.find('[name="description"]').val()
              var amount = $orderAdd.find('[name=amount]').val();
              var Studentroll = {
                orderstatus: orderstatus,
                studentuid: studentuid,
                studentname: studentname,
                mobile: mobile,
                classbonus: classbonus,
                classhours: classhours,
                courseid: courseid,
                coursename: coursename,
                orderdate: orderdate,
                description: description,
                amount: amount
              };
              ajaxMethod({
                    url: '/api/appointment',
                    type: 'post',
                    data: Studentroll,
                    success: function (data) {
                       window.location.reload();
                      //alert('添加成功')
                    }
                  });
            }
            var studentname = $contact.find('.name').text();
            var classhours = $orderAdd.find('[name=classhours]').val();
            if(studentname!=""||classhours!=""){
               add();
            }else{
              return false;
            }
          }
        },
        position: {
          width: 667,
          height: 352
        }
      })
     })

    function loadEnrollData(oruid, callback) {
      //console.log(oruid)
      ajaxMethod({
        url: '/api/appointment/' + oruid,
        dataType: 'json',
        success: function (data) {
         $orderEdit.find('[name=orderuid]').val(data.appointid);
          $orderEdit.find('[name=orderstatus]').val(data.orderstatus);
          $orderEdit.find('[name=studentuid]').val(data.studentuid);
          $orderEdit.find('[name=studentname]').val(data.studentname);
          $orderEdit.find('[name=ClassInNo]').val(data.mobile);
          $orderEdit.find('[name=classhours]').val(data.classhours);
          $orderEdit.find('[name=classbonus]').val(data.classbonus);
          $orderEdit.find('[name=courseid]').val(data.courseid);
          $orderEdit.find('[name=coursename]').val(data.coursename);
          $orderEdit.find('[name=description]').val(data.description);
          $orderEdit.find('[name=amount]').val(data.amount);
          var orderdate="";
          if(data.orderdate!="0000-00-00 00:00:00"){
            orderdate=data.orderdate.substr(0,10)
          }else{
            return "请选择日期"
          }
         $orderEdit.find('[name=orderdate]').val(orderdate);
          (typeof callback == 'function') && callback()
        }
      })
    }
   //编辑学生
  function bindSubmit(data) {
    if (FormCheck.childrenInputCheck($orderEdit.find('#J_enroll_wrap'))) {
        var appointid = $orderEdit.find('[name=orderuid]').val()
        var orderstatus = $orderEdit.find('[name=orderstatus]').val()
        var studentuid = $orderEdit.find('[name=studentuid]').val()
        var studentname = $orderEdit.find('[name="studentname"]').val()
        var ClassInNo = $orderEdit.find('[name=mobile]').val()
        var classhours = $orderEdit.find('[name=classhours]').val()
        var classbonus = $orderEdit.find('[name=classbonus]').val()
        var courseid = $orderEdit.find('[name=courseid]').val()
        var coursename = $orderEdit.find('[name=coursename]').val()
        var orderdate = $orderEdit.find('[name=orderdate]').val()
        var description = $orderEdit.find('[name="description"]').val()
        var amount = $orderEdit.find('[name=amount]').val()
        var Studentroll = {
          orderstatus: orderstatus,
          studentuid: studentuid,
          studentname: studentname,
          mobile: ClassInNo,
          classbonus: classbonus,
          classhours: classhours,
          courseid: courseid,
          coursename: coursename,
          orderdate: orderdate,
          description: description,
          amount: amount
        }
      if (appointid!=undefined) {
          ajaxMethod({
              url: '/api/appointment/'+appointid,
              type: 'put',
              data: $.extend(Studentroll, { appointid: appointid }),
              success: function (data) {
                   //alert('修改成功')
                 }
            });

          }

        }
    }
    var scheduleidarr=[];
    //以下是点击预约的controller
    var checkedList = new Array();
    function getEnrollList(arr) {
      ajaxMethod({
          url: '/api/schedules/teachertimes',
          type: 'get',
          dataType: 'json',
          data: arr,
          success: function (data, arr) {
           var $enrollmentTable1 = $J_teacher_appoint.find('.appoint-section23').html('');
            var days=data.days;
           $.each(days,function(index,item){
             var a=JSON.stringify(item.day)
             var day=(item.day).replace(/\-/g,"");
             var $div = $('<div data-id='+day+'></div>').appendTo($enrollmentTable1);
             $div.append('<h4 style="margin-top:43px;">' + item.day + ' (' + item.week + ') ' + '</h4>');
             var list=item.list;
             $.each(list,function(index2,item2){
                 var $p = $("<p style='height:41px;margin:24px 0;'></p>").appendTo($div);
                 var spn1 = $('<span class="spn1" style="display:inline-block;width:337px;line-height:24px;"></span>').appendTo($p);
                 spn1.append('<span style="width:161px;display:inline-block;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;position:relative;top:5px;">课程类型:' + item2.coursetypename + '</span>');
                 spn1.append('<span style="margin-top:10px;">课节名称：<span style="width:68px;display: inline-block;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;position: relative;top: 10px;">' + item2.name + '</span></span><br/>');
                 spn1.append('<span style="padding-right:29px;padding-left:4px;width:161px;display:inline-block;">时间:' + (item2.begintime.substr(11,5))+'~'+(item2.endtime.substr(11,5)) + '</span>');
                 spn1.append('<span style="" >剩余名额：<a class="quotas">' + item2.quotas + '</a></span>');
                 var $appointBtn1 = $('<input type="button" value="预约" class="btn btn-primary" style="position: relative;left: 14px;top: -11px;">').appendTo($p);
                 for(var i=0;i<scheduleidarr.length;i++){
                   if(scheduleidarr[i]==item2.scheduleid){
                     $appointBtn1.attr("disabled","disabled");
                     $appointBtn1.val("已预约");
                   }
                 }
                 var quotas=0;
                 $appointBtn1.on('click',function(){
                   quotas=$(this).prev('span').find('.quotas').html()-1;
                   if(quotas<0){quotas=0;}
                   $(this).prev('span').find('.quotas').html(quotas);
                   $(this).attr("disabled","disabled");
                   $(this).val("已预约");
                    var oruid= $J_teacher_appoint.find("#oruid").val();
                    var studentuid = $J_teacher_appoint.find(".studentuid").val();
                    $.ajax({
                        url: "/api/appointment/"+oruid+"/appint",
                        dataType: "json",
                        type: 'put',
                        data: {"scheduleid":item2.scheduleid},
                        success:function(data,status){
                          console.log(status)

                            if(status.code!=1){
                              $(this).css({
                                "background":"#ccc",
                                "border":"1px solid #ccc",
                                "color":"#fff"
                              });
                               $(this).html("已预约");
                            }


                       }
                    })
                  })

               })


             })

             //排序
            function big() {
                var tr = $enrollmentTable1.find("div");
                var initList = [], domArr = [];

                $.each(tr, function (a, k) {
                    initList[a] = $(this).attr('data-id');

                })
                /* 从小到大排序*/
                function bigToSmall() {
                    getDom();
                    $.each(domArr, function (i) {
                        $.each(domArr, function (j) {
                          if (domArr[i].attr('data-id') < domArr[j].attr('data-id')) {
                              mid = domArr[j]; domArr[j] = domArr[i]; domArr[i] = mid;
                          }

                        })
                    })
                    appendDom()
                }

                /*取出所有tr放进数组*/
                function getDom() {
                    $(tr).each(function (m) {
                        domArr[m] = $(this);
                    })
                }
                /*将数组中的tr插入tbody(原ul中的li自动删除。DOM元素的特性。) */
                function appendDom() {
                    $.each(domArr, function (d) {
                        $enrollmentTable1.append(domArr[d]);
                    })
                }
                bigToSmall();
              }
            big();

          }
        })
      }
    //按照类型选择老师
    function coursetypes() {
      ajaxMethod({
            url: '/api/coursetypes',
            type: "get",
            dataType: "json",
            success: function (data) {
            cource(data);
            }

        })
    function cource(data) {
          //console.log(data)
          var $cource = $('#cource').html('');
          $('<option>全部</option>').appendTo($cource);
          $cource.css({
              "width": "120px",
              "height": "30px",
              "border": "1px solid #ccc",
              "border-radius": "3px"

          });

          $.each(data, function (index,item) {
            //console.log(item.coursetypeuid);
            $('<option data-cuid='+item.coursetypeuid+'>' + item.coursetypename + '</option>').appendTo($cource);

          })
          $('#cource').on('change',function(){
            var sCoursetypename=$('#cource option:selected').val();
            var sCoursetypeid=$('#cource option:selected').attr('data-cuid');
            var getVal = $J_teacher_appoint.find("#J_date_search").val();
            appointTeacher(getVal.split('~')[0],getVal.split('~')[1],sCoursetypeid);
            })
        }
    }

    //按照时间选择老师
    function appointTeacher(begintime, endtime,sCoursetypeid) {

      if (begintime == undefined) {
        begintime = new Date().Format('YYYY-MM-DD')
        endtime = new Date(+new Date + 30 * 24 * 3600 * 1000).Format('YYYY-MM-DD')

        $J_teacher_appoint.find('#J_date_search').val(begintime + '~' + endtime)
      }

    ajaxMethod({
        url: '/api/schedules/teachers',
        data: {
          begintime:begintime,
          endtime:endtime,
          coursetypeid:sCoursetypeid
        },
       success: function (data) {
         formatData(data,sCoursetypeid);
         }
      })

    function formatData(data,sCoursetypeid){
        var $teacherListData = $J_teacher_appoint.find('#J_teacherlist_data').html('')
        $.each(data, function (index, item) {
             var studentname = $J_teacher_appoint.find('#studentname').val();
             var coursename = $J_teacher_appoint.find('#coursename').val();
             $J_teacher_appoint.find("#studentname1").html(studentname);
             $J_teacher_appoint.find("#coursename1").html(coursename);
           var teacheruid = item.teacherid;
           var $tr = $('<tr id="id' + item.teacherid + '" data-uid="' + item.teacherid + '"></tr>')
           $tr.append('<td>1</td>')
           $tr.append('<td>' + item.teachername + '</td>')
           //$tr.append('<td>' + item.mobile + '</td>')
           $tr.append('<td>' + item.begintime + '</td>')
           $tr.append('<td>' + item.endtime + '</td>')
           $tr.append('<td>' + item.times + '</td>')
           var $radioTd = $('<td></td>').appendTo($tr)
           var $radioIcon = $('<span class="icon icon-size-16 icon-radio" data-type="checkbox" style="postion:relative;left:3px;top:-1px;">\
               <input type="checkbox" name="teacher" data-checkedmax="1" value="1">\
               </span>').appendTo($radioTd);
           //点击小点
           $radioIcon.on('click', function () {
              var oruid= $J_teacher_appoint.find("#oruid").val();
              //alert(oruid);
              ajaxMethod({
                url:"/api/appointment/"+oruid+"/appints",
                type: "get",
                dataType: "json",
                success:function(data){
                   $.each(data,function(index,item){
                      scheduleidarr.push(item.scheduleid);

                   })

                }

              })



             if ($(this).hasClass('checked')) {
               $J_teacher_appoint.find('.timelist-search').hide()
               $J_teacher_appoint.find('.line').show();
             } else {
               $J_teacher_appoint.find('#J_teachername').text(item.teachername)
               $J_teacher_appoint.find('.timelist-search').show()
               $J_teacher_appoint.find('.line').hide();

               teacherlist(sCoursetypeid);
               $('#J_appointTimeList').click()
               var $parentDom = $J_teacher_appoint.find('.appoint-section').html('');
               var $teacherRemark=$J_teacher_appoint.find('.teacherRemark').html('');
               var id=item.teacherid;
               ajaxMethod({
                 url:"/api/teacher/"+id,
                 type:"get",
                 success:function(data){
                 $('<a>备注：</a><li style="display:inline-block;">'+data.remark1+' ,</li><li  style="display:inline-block;padding:0 4px;">'+data.remark2+'</li>').appendTo($teacherRemark);
                   }
                 })
               }
            })


           function teacherlist(sCoursetypeid) {
             var arr = {
               begintime: item.begintime,
               endtime: item.endtime,
               teacherid: item.teacherid,
               coursetypeid:sCoursetypeid
             }

             $('.timelist-search').show()
             $('.prompt').hide();
             $('#J_appointTimeList').click()
             getEnrollList(arr);
              }


           $teacherListData.append($tr)
           var $J_teacherlist_select = $J_teacher_appoint.find('#J_teacherlist_select');
           var len = $J_teacherlist_select.find('tr').length;
           for (var i = 1; i < len; i++) {
             $J_teacherlist_select.find('tr:eq(' + i + ') td:first').text(i);
           }

         })
       }


    $J_teacher_appoint.find('#J_date_search').on('change', function () {
        var getVal = $(this).val()
        appointTeacher(getVal.split('~')[0],getVal.split('~')[1])
    })
  }
// pagination($pagination, getorderinfos)
})
